#include "common.h"

key_t get_key()
{
    return ftok(PATHNAME, PROJ_ID);
}

int main()
{
    msg_struct msg ;
    int msgid, ret_value;
    int count = 5;

    cout << "this is a read_process" << endl;

    //创建一个新的信息队列
    key_t key = get_key();
    //检查这是否是一个新的消息队列
    msgid = msgget(key,IPC_CREAT | IPC_EXCL | 0666);
    if (msgid < 0)
    {
        perror("read msgget");
        return 1;
    }
    while(count--)
    {
        /*接收消息队列 msgrcv(int msqid, void *msgp, size_t msgsz, long msgtyp, int msgflg);
		* msgtyp：从消息队列内读取的消息形态。如果值为零，
		* 则表示消息队列中的所有消息都会被读取
		* msgflg : 0 表示阻塞等待，IPC_NOWAIT不等待
		*/  

        //从消息队列里面获取消息
        ret_value = msgrcv(msgid, &msg, sizeof(msg) - sizeof(long), 0, IPC_NOWAIT);
        //ret_value = msgrcv(msgid, &msg, sizeof(msg) - sizeof(long), 2, IPC_NOWAIT);
        cout << "read -> "<< "ret_value : " << ret_value << " type : " << msg.msg_type << " text : " << msg.text << endl;
        sleep(2);
    }
    int ret = msgctl(msgid, IPC_RMID, nullptr);
    if (ret < 0)
    {
        perror("msgctl");
        return 2;
    }
    cout << "msg delete sccessful!" << endl;
    return 0;
}
